﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Helpers;
using System.Configuration;
using System.Data.Common;
using Fcdbas.Core.DataAccess;
using Fcdbas.Core;
using Fcdbas.CodeBuilder.ety;
using System.Linq;
using DevExpress.XtraNavBar;


namespace Fcdbas.CodeBuilder
{
    public partial class MainForm : RibbonForm
    {
        ConnectionStringSettings cons;
        private string dbType = "MySql";
        bool isLoaded = false;                                                  //是否加载完毕
        private fnd_design_lu_tab currLugicUnit = new fnd_design_lu_tab();      //当前逻辑单元
        string currModule = string.Empty;
        private static readonly string StringFormat = "Uppercase,Lowercase,Invisble,Unformatted";
        private static readonly string NumberFormat = "Percentage,Currency,Invisible,Decimal,Unformatted";
        private static readonly string DateFormat = "Date,DateTime,Time,Unformatted";

        public MainForm()
        {
            
            InitializeComponent();
            InitSkinGallery();
            //this.WindowState = FormWindowState.Maximized;

        }
        void InitSkinGallery()
        {
            SkinHelper.InitSkinGallery(rgbiSkins, true);
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            //ConnectionStringSettings conSett = new ConnectionStringSettings();
            //conSett.ConnectionString = "Server=127.0.0.1;Port=3306;Database=Fcdbas;Uid=root;Pwd=1230;allow zero datetime=true";
            //DAL.ConnStrs.Add("MySql", conSett);
            //cons = DAL.ConnStrs[dbType];
            //DbConnectionStringBuilder conBuilder = new DbConnectionStringBuilder();
            //conBuilder.ConnectionString = conSett.ConnectionString;
            //conBuilder["Uid"] = "root";
            //conBuilder["Pwd"] = "1230";
            //DAL.AddConnStr(dbType, conBuilder.ConnectionString, null, "MySql.Data.MySqlClient");
            DAL dal = DAL.Create("MySql");
            dal.Session.Open();

            RefreshData();

            isLoaded = true;
            
        }

        private void RefreshData()
        {
            IList<fnd_design_lu_tab> ilLuTab = Entity<fnd_design_lu_tab>.FindAll();
            IEnumerable<IGrouping<string, fnd_design_lu_tab>> ilGroup = ilLuTab.GroupBy(pallet => pallet.module);
            int iModule = 0; int iLogicUnit = 0;
            string sModule = string.Empty; string sLuName = string.Empty;
            try
            {
                tvModule.Nodes.Clear();
                foreach (IGrouping<string, fnd_design_lu_tab> grp in ilGroup)
                {
                    //添加 Module
                    sModule = grp.Key;

                    TreeNode tnModule = new TreeNode();
                    tnModule.Tag = sModule;
                    tnModule.Text = sModule;
                    tnModule.Name = sModule;
                    tnModule.ImageIndex = 13;
                    #region 添加逻辑单元
                    iLogicUnit = 0;
                    NavBarItem[] nbiLogicUnit = new NavBarItem[(from dt in ilLuTab
                                                                where dt.module == sModule
                                                                select dt).Count()];
                    foreach (fnd_design_lu_tab etyLu in (from dt in ilLuTab
                                                         where dt.module == sModule
                                                         select dt))
                    {
                        sLuName = etyLu.lu_name;
                        TreeNode tnLogicUnit = new TreeNode();
                        tnLogicUnit.Text = sLuName;
                        tnLogicUnit.Tag = etyLu;
                        
                        tnModule.Nodes.Add(tnLogicUnit);
                        iLogicUnit++;
                    }
                    #endregion
                    tvModule.Nodes.Add(tnModule);
                    iModule++;
                }
            }
            catch (Exception ex)
            {
            }
        }

        #region 模块

        //添加 module
        private void iNew_ItemClick(object sender, ItemClickEventArgs e)
        {
            NewModel fmNewModel = new NewModel();
            if (fmNewModel.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //fnd_design_lu_tab etyLogicUnit = fmNewModel.newEtyLogicUnit;
                //TreeNode tnLogicUnit = new TreeNode();
                //tnLogicUnit.Text = etyLogicUnit.lu_name;
                //tnLogicUnit.Tag = etyLogicUnit.lu_name;
                //tvModule.Nodes.Add(tnLogicUnit);
                RefreshData();
            }
        }

        //删除module
        private void deleteModuleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string sModule = currModule;

            if (MessageBox.Show(string.Format("是否确定删除模块[{0}]?", sModule), "", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }
            fnd_design_lu_tab eyLuTab = new fnd_design_lu_tab();
            Dictionary<SalString, SalString> pars = new Dictionary<SalString, SalString>();
            pars.Add("@module", sModule);

            int iRst = eyLuTab.Execute("delete from fnd_design_attribute_tab where module=@module", pars);
            iRst = eyLuTab.Execute("delete from fnd_design_lu_tab where module=@module", pars);
            if (iRst == 0)
            {
                MessageBox.Show("保存失败。");
                return;
            }
            MessageBox.Show("保存成功。");
            tvModule.Nodes.Remove(tvModule.SelectedNode);
            
        }

        #endregion 

        private void iExit_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.Close();
        }

        #region 逻辑单元

        //添加 逻辑单元
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            NewLogicUnit fmLogicUnit = new NewLogicUnit(currModule);
            if (fmLogicUnit.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                fnd_design_lu_tab etyLogicUnit = fmLogicUnit.newEtyLogicUnit;
                TreeNode tnLogicUnit = new TreeNode();
                tnLogicUnit.Text = etyLogicUnit.lu_name;
                tnLogicUnit.Tag = etyLogicUnit;
                tvModule.SelectedNode.Nodes.Add(tnLogicUnit);
            }
        }

        //保存逻辑单元
        private void iSaveAs_ItemClick(object sender, ItemClickEventArgs e)
        {
            ggcDataGrid.EndUpdate();
            txtTableName.Focus();
            //保存逻辑单元信息
            currLugicUnit.package_name = txtPackage.Text;
            currLugicUnit.view_name = txtView.Text;
            currLugicUnit.table_name = txtTableName.Text;
            currLugicUnit.Save();


            //保存表定义
            IList<fnd_design_attribute_tab> ilAttrib = bindingSource1.DataSource as List<fnd_design_attribute_tab>;
            int idx = 0;
            foreach (fnd_design_attribute_tab eyAttrib in ilAttrib)
            {
                eyAttrib.column_index = idx;
                idx++;
                eyAttrib.lu_name = currLugicUnit.lu_name;
                eyAttrib.module = currLugicUnit.module;
                eyAttrib.Save();
                eyAttrib.Execute("commit;");
            }
            
            MessageBox.Show("保存成功");
        }

        private void bbiDelLu_ItemClick(object sender, ItemClickEventArgs e)
        {
            deleteLogicUnit();
        }
        private void tsmDelLogicUnit_Click(object sender, EventArgs e)
        {
            deleteLogicUnit();
        }

        //删除逻辑单元
        private void deleteLogicUnit()
        {
            TreeNode currNode = tvModule.SelectedNode;
            if (currNode.Parent != null)
            {
                if (MessageBox.Show(string.Format("是否确定删除逻辑单元[{0}]?", currLugicUnit.lu_name), "", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.Cancel)
                {
                    return;
                }
                fnd_design_lu_tab eyLuTab = new fnd_design_lu_tab();
                Dictionary<SalString, SalString> pars = new Dictionary<SalString, SalString>();
                pars.Add("@module", currLugicUnit.module);
                pars.Add("@lu_name", currLugicUnit.lu_name);

                int iRst = eyLuTab.Execute("delete from fnd_design_attribute_tab where module=@module and lu_name=@lu_name", pars);
                iRst = eyLuTab.Execute("delete from fnd_design_lu_tab where module=@module and lu_name=@lu_name", pars);
                if (iRst == 0)
                {
                    MessageBox.Show("保存失败。");
                    return;
                }
                MessageBox.Show("保存成功。");
                currNode.Parent.Nodes.Remove(currNode);
                //RefreshData();
            }
        }

        //选中逻辑单元
        private void tvModule_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode currNode = tvModule.SelectedNode;
            if (currNode.Parent != null)
            {
                if (isLoaded)
                {
                    //选中逻辑单元
                    if (groupBox1.Visible == false)
                    {
                        groupBox1.Visible = true;
                        ggcDataGrid.Visible = true;
                    }
                    currLugicUnit = tvModule.SelectedNode.Tag as fnd_design_lu_tab;
                    if (currLugicUnit == null)
                    {
                        currLugicUnit = new fnd_design_lu_tab();
                    }
                    ggcDataGrid.Visible = true;
                    groupBox1.Visible = true;
                    bbiDelLu.Enabled = true;
                    txtPackage.Text = currLugicUnit.package_name;
                    txtTableName.Text = currLugicUnit.table_name;
                    txtView.Text = currLugicUnit.view_name;
                    //取得表信息
                    IList<fnd_design_attribute_tab> ilCurrAttrib = Entity<ety.fnd_design_attribute_tab>.FindAll("module='" + currLugicUnit.module + "' AND lu_name='" + currLugicUnit.lu_name + "'"," column_index", "", 0, 0);
                    if (ilCurrAttrib.Count <= 0)
                    {
                        fnd_design_attribute_tab eyAttr = new fnd_design_attribute_tab();
                        ilCurrAttrib.Add(eyAttr);
                    }
                    bindingSource1.DataSource = ilCurrAttrib;
                }
            }
            else
            {
                currModule = tvModule.SelectedNode.Tag.ToString();
            }
        }
        #endregion 

        #region 导出
        private void iExpSto_ItemClick(object sender, ItemClickEventArgs e)
        {
            fnd_design_lu_tab eyLuTab = new fnd_design_lu_tab();
            string sql = "FndDesignLu_GeLuLogical___(:logical_text_ ,:module_ ,:lu_name_ ,:block_id_)";
            Dictionary<SalString, SalString> pars = new Dictionary<SalString, SalString>();
            pars.Add("logical_text_", "");
            pars.Add("module_", currLugicUnit.module);
            pars.Add("lu_name_", currLugicUnit.lu_name);
            pars.Add("block_id_", "DBKARG_IN");

            int iRst = eyLuTab.Execute(sql, pars,CommandType.StoredProcedure);

            //string strSto =System.Text.Encoding.ASCII.GetString(currLugicUnit.storage_text);
            string strSto = pars["logical_text_"].Value;
            string strFile=string.Format(@"..\lib\{0}Storage.txt",currLugicUnit.lu_name);
            FileHelper.GenerateFile(strFile, strSto, "");
            MessageBox.Show(string.Format("成功导出Storage文件：{0}",strFile));
        }

        private void iExpLu_ItemClick(object sender, ItemClickEventArgs e)
        {
            string strSto =System.Text.Encoding.ASCII.GetString(currLugicUnit.logical_text);
            string strFile=string.Format(@"..\lib\{0}Logical.txt",currLugicUnit.lu_name);
            FileHelper.GenerateFile(strFile, strSto, "");
            MessageBox.Show(string.Format("成功导出Logical文件：{0}",strFile));
        }
        #endregion 

        //点击树
        private void tvModule_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button.ToString() == "Right")
            {
                TreeNode currNode = tvModule.SelectedNode;
                if (currNode.Parent == null)
                {
                    tsmDeleModule.Visible = true;
                    tsmNewLogicUnit.Visible = true;
                    tsmDelLogicUnit.Visible = false;
                    if (groupBox1.Visible)
                    {
                        groupBox1.Visible = false;
                        ggcDataGrid.Visible = false;
                    }
                }
                else
                {
                    tsmDeleModule.Visible = false;
                    tsmNewLogicUnit.Visible = false;
                    tsmDelLogicUnit.Visible = true;
                }
                this.cmsLogicUnit.Show(MousePosition);
            }

        }

        private void ricbDateType_SelectedValueChanged(object sender, EventArgs e)
        {
            //return;
            this.rbFormat.Items.Clear();
            if (!(bindingSource1 != null && bindingSource1.Current != null && bindingSource1.Current is fnd_design_attribute_tab))
                return;
            string cellValue = ((DevExpress.XtraEditors.ComboBoxEdit)sender).EditValue.ToString();
            ((fnd_design_attribute_tab)bindingSource1.Current).data_type = cellValue;
            switch (cellValue)
            {
                case "String":
                    // string s = "Uppercase,Lowercase,Invisble,Unformatted";
                    string[] s1 = StringFormat.Split(',');
                    foreach (string ss in s1)
                    {
                        this.rbFormat.Items.Add(ss);
                    }

                    break;
                case "Number":

                    foreach (string ss in NumberFormat.Split(','))
                    {
                        this.rbFormat.Items.Add(ss);
                    }
                    break;
                case "Date":

                    foreach (string ss in DateFormat.Split(','))
                    {
                        this.rbFormat.Items.Add(ss);
                    }

                    break;
            }
            if (this.rbFormat.Items.Count > 0 && this.rbFormat.Items[0] != null)
                ((fnd_design_attribute_tab)bindingSource1.Current).data_format = this.rbFormat.Items[0].ToString();
        }

        private void rbAttribute_EditValueChanged(object sender, EventArgs e)
        {
            //rbPrompt.tex
            //rbAttribute.GetDisplayText(string s);
        }

        private void bindingSource1_AddingNew(object sender, AddingNewEventArgs e)
        {
            if (bindingSource1.Current != null)
            {
                fnd_design_attribute_tab eyAttrib = bindingSource1.Current as fnd_design_attribute_tab;
                eyAttrib.lu_name = currLugicUnit.lu_name;
                eyAttrib.module = currLugicUnit.module;
            }
        }

        private void gridView1_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            Console.WriteLine("gridView1_InitNewRow");
        }

        private void gridView1_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            Console.WriteLine("gridView1_RowUpdated");
        }

        private void bindingSource1_CurrentChanged(object sender, EventArgs e)
        {
            Console.WriteLine("bindingSource1_CurrentChanged");
        }

        private void bindingSource1_CurrentItemChanged(object sender, EventArgs e)
        {
            Console.WriteLine("bindingSource1_CurrentItemChanged");
        }

        private void bindingNavigator1_ItemAdded(object sender, ToolStripItemEventArgs e)
        {
            List<fnd_design_attribute_tab> list = bindingSource1.DataSource as List<fnd_design_attribute_tab>;
            fnd_design_attribute_tab fa = new fnd_design_attribute_tab();
            list.Add(fa);
            ggcDataGrid.RefreshDataSource();
        }

        private void bindingNavigator1_ItemRemoved(object sender, ToolStripItemEventArgs e)
        {
            if (bindingSource1.Current != null)
            {
                fnd_design_attribute_tab fa = bindingSource1.Current as fnd_design_attribute_tab;
                fa.Delete();
                ggcDataGrid.RefreshDataSource();
            }
        }

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
            List<fnd_design_attribute_tab> list = bindingSource1.DataSource as List<fnd_design_attribute_tab>;
            fnd_design_attribute_tab fa = new fnd_design_attribute_tab();
            //fa.attribute = " ";
            list.Add(fa);
            ggcDataGrid.RefreshDataSource();
        }

        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {
            fnd_design_attribute_tab fd = bindingSource1.Current as fnd_design_attribute_tab;
            fd.Delete();
            List<fnd_design_attribute_tab> list = bindingSource1.DataSource as List<fnd_design_attribute_tab>;
            list.Remove(fd);
            ggcDataGrid.RefreshDataSource();
        }





        }
}